package com.css.fxfzdzzh.login.controller;

import com.alibaba.fastjson.JSONArray;
import com.css.fxfzdzzh.base.response.RestResponse;
import com.css.fxfzdzzh.config.property.FxfzConfig;
import com.css.fxfzdzzh.constants.FxfzConstants;
import com.css.fxfzdzzh.constants.LoginStatusCodeEnum;
import com.css.fxfzdzzh.constants.R;
import com.css.fxfzdzzh.login.security.LoginSecretPool;
import com.css.fxfzdzzh.login.service.LoginService;
import com.css.fxfzdzzh.login.viewobjects.LoginParams;
import com.css.fxfzdzzh.login.viewobjects.LoginStatus;
import com.css.fxfzdzzh.util.*;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.slw.common.helper.PropsHelper;
import org.slw.sso.config.SsoConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Slf4j
@RestController
@RequestMapping("/sys")
public class LoginController {
    @Autowired
    FxfzConfig fxfzConfig;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Autowired
    LoginService loginService;

    private static final String SESSION_RSAMAP_KEY = "PLATFORM_RSAMAP";
    private static final String PUBLIC_KEY = "PUBLIC_KEY";
    private static final String SESSION_ISCAPTCHA_KEY = "PLATFORM_ISCAPTCHA";
    private static final String SESSION_CAPTCHA_KEY = "PLATFORM_CAPTCHA";
    //读取配置文件
    Properties CONFIG_PROP = PropsHelper.loadProps("slw-config.properties");

    @PostMapping("/loginIn")
    public LoginStatus loginLocal(@RequestBody LoginParams loginParams, HttpServletRequest request){
            LoginStatus status = new LoginStatus();
        try {
            Map<String, String> keyMap = (Map<String, String>) request.getSession().getAttribute(SESSION_RSAMAP_KEY);
            //session超时
            /*if (PlatformObjectUtils.isEmpty(keyMap)) {
                keyMap = LoginSecretPool.getKeys();
                request.getSession().setAttribute(SESSION_RSAMAP_KEY, keyMap);
            } else {*/
                keyMap = LoginSecretPool.getKeys();
                boolean isCaptchaSuccess = checkCaptcha(request, loginParams.getCaptcha());
                if (!isCaptchaSuccess) {
                    status.setStatus(LoginStatusCodeEnum.CAPTHCA_ERROR.getCode());
                    status.setMessage(LoginStatusCodeEnum.CAPTHCA_ERROR.getMessage());
                    return status;
                }
                String privateKey = keyMap.get(PlatformRSAUtils.PRIVATE_KEY);
                String clientIp = PlatformHttpRequestUtils.getClientIp(request);
                status = loginService.loginIn(loginParams.getUserCode(), loginParams.getPassword(), privateKey, clientIp, request);
            /*}*/

        }catch (Exception e){
            e.printStackTrace();
            status.setStatus(LoginStatusCodeEnum.ERROR.getCode());
            status.setMessage(LoginStatusCodeEnum.ERROR.getMessage());
        }
        if (status.isSuccess()) {
            HttpSession session = request.getSession();
            session.setAttribute(FxfzConstants.CUR_USER_ID_IN_SESSION, status.getUserId());
        }
        return status;
    }

    private boolean checkCaptcha(HttpServletRequest request, String captcha) {
        Boolean isCaptcha = fxfzConfig.getIsCaptcha();
        if (isCaptcha) {
            String sessionCaptchaValue = (String)request.getSession().getAttribute(SESSION_CAPTCHA_KEY);
            boolean isSuccess = PlatformObjectUtils.isNotEmpty(sessionCaptchaValue) ? captcha.toLowerCase().equals(sessionCaptchaValue.toLowerCase()) : false;
            request.getSession().removeAttribute(SESSION_CAPTCHA_KEY);
            return isSuccess;
        }
        return true;
    }

    @GetMapping("/app/getSession")
    public ResponseEntity<String> getSession(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        /*String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");*/
        Map<String, Object> paramMap = new HashMap<>(10);
        paramMap.put("loginName","123123");
        paramMap.put("password","123123");
        paramMap.put("logintype","loginname");
        ResponseEntity<String> stringResponseEntity = restTemplateUtil.sendHttpRequest("http://10.7.208.228:8090/sso/login.action", paramMap);
        return stringResponseEntity;

    }


    @GetMapping("/login")
    public void login(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
        StringBuffer pattern = new StringBuffer();
        Map<String, String> keyMap = LoginSecretPool.getKeys();
        request.getSession().setAttribute(SESSION_RSAMAP_KEY, keyMap);
        //这是公钥
        model.addAttribute(PUBLIC_KEY, keyMap.get(PlatformRSAUtils.PUBLIC_KEY));
        //验证码是否启用
        Boolean isCaptcha = fxfzConfig.getIsCaptcha();
        model.addAttribute(SESSION_ISCAPTCHA_KEY, isCaptcha);

        /*String contextPath = request.getContextPath();
        model.addAttribute("title", "此处是系统名称");
        model.addAttribute("copyright", "@");
        model.addAttribute("contextPath", contextPath);*/

        pattern.append("密码最小长度为"+ fxfzConfig.getPwdLength());
        if ("unlimited".equals(fxfzConfig.getPwdRule())) {
            ;
        } else if ("numeric".equals(fxfzConfig.getPwdRule())) {
            pattern.append(",密码组合模式为数字");
        } else if ("letter".equals(fxfzConfig.getPwdRule())) {
            pattern.append(",密码组合模式为字母");
        } else if ("chars".equals(fxfzConfig.getPwdRule())) {
            pattern.append(",密码组合模式为特殊字符");
        } else if ("anytwo".equals(fxfzConfig.getPwdRule())) {
            pattern.append(",密码组合模式为字母、数字、特殊字符");
        }
        model.addAttribute("tip", pattern.toString());
        response.sendRedirect("http://10.13.155.117:8081/index");
    }
    @GetMapping("/getToken")
    public R pclogin(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String userID = PlatformSessionContext.getUserID();
        String token = PlatformJwtUtils.createToken(userID);
        session.setAttribute("pcToken",token);
        return R.ok().put("token",token).put("userId",userID);
    }


    @PostMapping("loginBackDoor")
    public RestResponse loginBackDoor(){
        RestResponse restResponse = null;
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("loginParam","xxx");
            Properties CONFIG_PROP = PropsHelper.loadProps("slw-config.properties");
            String sysId = CONFIG_PROP.getProperty("app.system.id");
            paramMap.put("sysId", sysId);
            ResponseEntity<String> jsonStr = restTemplateUtil.sendHttpRequest("/xxx/xxx?loginParam={xxx}&sysId={sysId}",paramMap);
            JSONArray jsonArray = JSONArray.parseArray(jsonStr.getBody());
            //解析jsonArray

            //把解析结果返回前断
            restResponse = RestResponse.succeed("登录成功");
        }catch (Exception e){
            e.printStackTrace();
            restResponse = RestResponse.fail("登录失败！");
        }
        return restResponse;
    }
    /**
     * 退出
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.removeAttribute(FxfzConstants.CUR_USER_ID_IN_SESSION);
        String backUrl = CONFIG_PROP.getProperty("frontUrl");
        String retUrl = SsoConfig.getInstance().getQuitUrl() + "?toUrl=" + backUrl;
        return R.ok().put("retUrl",retUrl);
    }
}

